import qs from 'qs';

/**
 * 外部链接跳转过来统一对参数进行base64编码后以qs={query}的形式传递过来
 * query为base64编码后的结果
 */

// 获取url参数并解析
export function getQueryParams() {
  const { qs: qsStr, ...rest } = qs.parse(window.location.search.substr(1));

  let queryObj: RecordItem = {};

  if (qsStr) {
    queryObj = qs.parse(decodeURIComponent(window.atob(qsStr as string)));
  }

  return { ...queryObj, ...rest };
}

// 将对象转成url参数并且Base64加密
export function transformQueryParams(params: Record<string, any>) {
  return window.btoa(encodeURIComponent(qs.stringify(params)));
}

// 将对象参数与现有url参数合并后转换
export function transformPrefixQueryParams(params: Record<string, any>) {
  return window.btoa(
    encodeURIComponent(
      qs.stringify({
        ...getQueryParams(),
        ...params,
      }),
    ),
  );
}
